package com.mobile.challenge.ui.report.my

import android.app.DatePickerDialog
import android.graphics.Color
import android.os.Bundle
import androidx.lifecycle.Observer
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.components.Legend
import com.google.android.material.tabs.TabLayout
import com.mobile.challenge.R
import com.mobile.challenge.databinding.FragmentMyReportBinding
import com.mobile.challenge.ui.report.model.PeriodType
import com.mobile.frame.mvvmframe.base.BaseFragment
import java.text.SimpleDateFormat
import java.util.*


/**
 * @Author Touge
 * @Date 2020/9/15 22:36
 * @Description
 */
class MyReportFragment : BaseFragment<MyReportViewModel, FragmentMyReportBinding>(), TabLayout.OnTabSelectedListener {

    private var currentCalendar = Calendar.getInstance()
    private var periodType = PeriodType.DAILY

    companion object {
        fun newInstance(): MyReportFragment {
            val args = Bundle()

            val fragment = MyReportFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_my_report
    }

    override fun initData(savedInstanceState: Bundle?) {
        initUI()
        mViewModel.pieData.observe(this, Observer { data ->
            mBinding.pieChart.data = data
            if (mViewModel.totalCount > 0) {
                mBinding.pieChart.centerText = mViewModel.totalCount.toString()
            }
            // 展开动画
            mBinding.pieChart.animateY(1000, Easing.EaseInOutQuad)
            mBinding.pieChart.invalidate()
        })
    }

    private fun initUI() {
        // 初始化饼状图属性
        with(mBinding.pieChart) {
            // 显示百分比
            setUsePercentValues(false)
            description.isEnabled = false
            // 设置边距
            setExtraOffsets(40f, 10f, 40f, 5f)
            setDrawCenterText(false)

            // 展开动画
            animateY(1000, Easing.EaseInOutQuad)

            // 图例
            legend.verticalAlignment = Legend.LegendVerticalAlignment.TOP
            legend.horizontalAlignment = Legend.LegendHorizontalAlignment.RIGHT
            legend.orientation = Legend.LegendOrientation.VERTICAL
            legend.setDrawInside(false)
            legend.xEntrySpace = 7f
            legend.yEntrySpace = 0f
            legend.yOffset = 0f

            // label 文字样式
            setDrawEntryLabels(false)
            setEntryLabelColor(Color.BLACK)
            setEntryLabelTextSize(12f)

            // 关闭内环
//            isDrawHoleEnabled = false

            // 关闭旋转
            isRotationEnabled = false
        }

        // 初始化当前时间
        mBinding.currentTimeText.setOnClickListener {
            showDatePickDialog()
        }

        updateText()

        // 注册周期选择监听
        mBinding.periodTabLayout.addOnTabSelectedListener(this)
        mViewModel.updateData(periodType, currentCalendar)
    }

    /**
     * 显示时间选择器
     */
    private fun showDatePickDialog() {
        val datePickerDialog = DatePickerDialog(
                requireContext(),
                DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
                    currentCalendar = Calendar.getInstance().apply {
                        set(year, month, dayOfMonth, 0, 0, 0)
                    }
                    updateText()
                    mViewModel.updateData(periodType, currentCalendar)
                },
                currentCalendar.get(Calendar.YEAR),
                currentCalendar.get(Calendar.MONTH),
                currentCalendar.get(Calendar.DAY_OF_MONTH)
        )
        val datePicker = datePickerDialog.datePicker
        datePicker.maxDate = System.currentTimeMillis()
        try {
            datePickerDialog.show()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 更新文字
     */
    private fun updateText() {
        mBinding.currentTimeText.text = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                .format(currentCalendar.timeInMillis)
    }

    override fun onTabReselected(tab: TabLayout.Tab?) {

    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {

    }

    override fun onTabSelected(tab: TabLayout.Tab?) {
        periodType = when (tab?.position) {
            0 -> {
                PeriodType.DAILY
            }
            1 -> {
                PeriodType.WEEKLY
            }
            else -> {
                PeriodType.MONTH
            }
        }
        mViewModel.updateData(periodType, currentCalendar)
    }

}